﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KylinORM.Mapper.Base;
using KylinORM.Utils;

namespace KylinORM.Aspect.Definition
{
    /// <summary>
    /// 已知实体类型的字段描述
    /// </summary>
    internal static class EntityDefinitionMap
    {
        private static object lockHelper = new object();        
        private static Dictionary<Type, EntityDefinition> entityDefMap = new Dictionary<Type, EntityDefinition>();

        private static IEntityDefinitionRule entityDefRule = new EntityDefinitionRule();
        /// <summary>
        /// 设置全局实体类型的字段描述
        /// </summary>
        internal static IEntityDefinitionRule EntityDefinitionRule
        {
            set
            {
                entityDefRule = value;
            }
        }

        /// <summary>
        /// 得到指定实体类型的字段描述
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <returns>字段描述</returns>
        internal static EntityDefinition GetEntityDefinition<T>()
        {
            return GetEntityDefinition<T>(entityDefRule);
        }
        /// <summary>
        /// 得到指定实体类型的字段描述
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="definitionRule">实体映射规则</param>
        /// <returns>字段描述</returns>
        internal static EntityDefinition GetEntityDefinition<T>(IEntityDefinitionRule definitionRule)
        {
            Type entityType = typeof(T);

            if (entityDefMap.Keys.Contains(entityType))
                return ((ICloneable<EntityDefinition>)entityDefMap[entityType]).Clone();

            lock (lockHelper)
            {
                if (entityDefMap.Keys.Contains(entityType))
                    return entityDefMap[entityType];

                EntityDefinition entityDef = new EntityDefinition(entityType, definitionRule ?? entityDefRule);
                entityDefMap.Add(entityType, entityDef);
                return ((ICloneable<EntityDefinition>)entityDefMap[entityType]).Clone();
            }
        }



    }
}
